# -*- python -*-
# ex: set filetype=python:

import os

from buildbot.plugins import *
from buildbot.process.results import statusToString

from flask import Flask
from flask import render_template

NUM_BUILDERS = 2

c = BuildmasterConfig = {}

####### WORKERS

c['workers'] = [
  worker.Worker("example-worker", "pass"),
  worker.Worker("shutdown-worker", "pass"),
]
c['protocols'] = {'pb': {'port': 9989}}


####### CHANGESOURCES

c['change_source'] = []
c['change_source'].append(changes.GitPoller(
        'https://github.com/buildbot/hello-world.git',  # the buildbot clone of pyflakes
        workdir='gitpoller-workdir', branch='master',
        pollInterval=300))

####### SCHEDULERS

c['schedulers'] = []
c['schedulers'].append(schedulers.SingleBranchScheduler(
                            name="all",
                            change_filter=util.ChangeFilter(branch='master'),
                            treeStableTimer=None,
                            builderNames=["runtests" + str(i) for i in range(NUM_BUILDERS)]))

c['schedulers'].append(schedulers.ForceScheduler(
                            name="force",
                            builderNames=["runtests", "slowruntests"]))

c['schedulers'].append(schedulers.ForceScheduler(
    name="custom",
    builderNames=["runtests"],
    buttonName="Start Custom Build",
    codebases = [util.CodebaseParameter(
        codebase='', project=None,
        branch=util.ChoiceStringParameter(
            name="branch",
            label="Branch",
            strict=False,
            choices=["master", "dev"],
            autopopulate={
              'master': {
                'build_name': 'master',
              },
              'dev': {
                'build_name': 'dev',
              }
            }
    ))],
    properties=[
        util.StringParameter(
            name="build_name",
            label="Name of the Build release.",
            default="")]))

c['schedulers'].append(schedulers.ForceScheduler(
                            name="force-neverruntests",
                            builderNames=["neverruntests"]))

####### BUILDERS

factory = util.BuildFactory()
factory.addStep(steps.Git(repourl='https://github.com/buildbot/hello-world.git',
                          mode='incremental'))
factory.addStep(steps.ShellCommand(command=["trial", "hello"],
                                   env={"PYTHONPATH": "."}))

slowfactory = util.BuildFactory()
slowfactory.addStep(steps.Git(repourl='https://github.com/buildbot/hello-world.git',
                              mode='incremental'))
slowfactory.addStep(steps.ShellCommand(command=["trial", "hello"],
                                       env={"PYTHONPATH": "."}))
slowfactory.addStep(steps.ShellCommand(command=["sleep", "10"]))


c['builders'] = []
c['builders'].append(
    util.BuilderConfig(name="runtests",
                       tags=['runt'],
                       workernames=["example-worker"],
                       factory=factory))
c['builders'].append(
    util.BuilderConfig(name="slowruntests",
                       tags=['slow', 'runt'],
                       workernames=["example-worker"],
                       factory=slowfactory))
c['builders'].append(
    util.BuilderConfig(name="neverruntests",
                       tags=['slow', 'runt', 'never'],
                       workernames=["shutdown-worker"],
                       factory=factory))

for i in range(NUM_BUILDERS):
    c['builders'].append(
        util.BuilderConfig(name="runtests" + str(i),
                           tags=[str(i), 'runt'],
                           workernames=["example-worker"],
                           factory=factory))


####### PROJECT IDENTITY

c['title'] = "Pyflakes"
c['titleURL'] = "https://launchpad.net/pyflakes"
c['buildbotURL'] = "http://localhost:8011/"

# we're not using the default port so that it would not accidentally conflict
# with any development instances of buildbot on developer machines
c['www'] = {
    "port": 8011,
    "change_hook_dialects": {'base': True},
    "plugins": {
        "waterfall_view": {},
        "console_view": {},
        "grid_view": {},
        "wsgi_dashboards": [],
    },
    "ui_default_config": {
        'Builders.buildFetchLimit': 201,
        'Waterfall.scaling_waterfall': 1.234
    }
}

c['buildbotNetUsageData'] = None

####### DB URL

c['db'] = {
    'db_url': "sqlite:///state.sqlite",
}

authz = util.Authz(
  allowRules=[
  ],
  roleMatchers=[
    util.RolesFromEmails(admins=["my@email.com"])
  ]
)
auth=util.UserPasswordAuth({'my@email.com': b'mypass'})
c['www']['auth'] = auth
c['www']['authz'] = authz

# WSGI dashboard

dashboardapp = Flask('test', root_path=os.path.dirname(__file__))
# this allows to work on the template without having to restart Buildbot
dashboardapp.config['TEMPLATES_AUTO_RELOAD'] = True


@dashboardapp.route("/index.html")
def main():
    # This code fetches build data from the data api, and give it to the
    # template
    builders = dashboardapp.buildbot_api.dataGet("/builders")

    builds = dashboardapp.buildbot_api.dataGet("/builds", limit=20)

    # properties are actually not used in the template example, but this is
    # how you get more properties
    for build in builds:
        build['properties'] = dashboardapp.buildbot_api.dataGet(
            ("builds", build['buildid'], "properties"))

        build['results_text'] = statusToString(build['results'])

    graph_data = [
        {'x': 1, 'y': 100},
        {'x': 2, 'y': 200},
        {'x': 3, 'y': 300},
        {'x': 4, 'y': 0},
        {'x': 5, 'y': 100},
        {'x': 6, 'y': 200},
        {'x': 7, 'y': 300},
        {'x': 8, 'y': 0},
        {'x': 9, 'y': 100},
        {'x': 10, 'y': 200},
    ]

    # dashboard.html is a template inside the template directory
    return render_template('dashboard.html', builders=builders, builds=builds,
                           graph_data=graph_data)


c['www']['plugins']['wsgi_dashboards'] = [
    {
        'name': 'dashboard',
        'caption': 'Test Dashboard',
        'app': dashboardapp,
        'order': 5,
        'icon': 'ChartArea'
    }
]
